/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.common.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.Encodes;
import cn.net.ecode.common.utils.FileUtils;
import cn.net.ecode.common.utils.StringUtils;

/**
 * 用户文件下载
 * @author ThinkGem
 * @version 2015-3-16
 */
public class UserfilesDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());

	public void fileOutputStream(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String filePath = Encodes.urlDecode(request.getRequestURI());
		filePath = StringUtils.substringAfter(filePath, Global.USERFILES_BASE_URL);
		
		// 如果开启了文件预览，则调用weboffice组件。
		if (Global.TRUE.equals(Global.getConfig("userfiles.openPreview", Global.TRUE))){
		
			// WebOffice点聚中间件 http://www.dianju.cn/products/middleware/weboffice
			String docType = null;
			if (StringUtils.endsWithAny(filePath, ".doc", ".docx")){
				docType = "doc";
			}else if (StringUtils.endsWithAny(filePath, ".xls", ".xlsx")){
				docType = "xls";
			}else if (StringUtils.endsWithAny(filePath, ".ppt", ".pptx")){
				docType = "ppt";
			}else if (StringUtils.endsWithAny(filePath, ".wps", ".wpt")){
				docType = "wps";
			}else if (StringUtils.endsWithAny(filePath, ".pdf")){
				docType = "pdf";
			}
			if (docType != null){
				request.setAttribute("docType", docType);
				request.getRequestDispatcher("/static/weboffice/preview.jsp").forward(request, response);
				return;
			}
			if (StringUtils.endsWithAny(filePath, ".download")){
				filePath = StringUtils.substringBeforeLast(filePath, ".download");
			}
			
		}
		
		// 下载文件
		File file = new File(FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filePath));
		logger.debug("Download file: {}  Range: {}", file, request.getHeader("Range"));
//		try {
//			response.setHeader("Content-Type", "application/octet-stream");
//			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
//			FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
//			return;
//		} catch (FileNotFoundException e) {
//			request.setAttribute("message", "文件不存在");
//			request.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(request, response);
//		}
		String fileName = file.getName();
		// 替换到百度编辑器上传的日期时间后缀
		String filenameTimeSuffix = StringUtils.substringAfterLast(FileUtils.getFileNameWithoutExtension(fileName), "_$");
		if (NumberUtils.isNumber(filenameTimeSuffix)){
			fileName = StringUtils.replace(fileName, "_$" + filenameTimeSuffix, "");
		}
		String error = FileUtils.downFile(file, request, response, fileName);
		if (error != null){
			request.setAttribute("message", error);
			request.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(request, response);
		}
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		fileOutputStream(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		fileOutputStream(request, response);
	}
	
}
